﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using BuyTrainTicket.Resources;
using System.IO.IsolatedStorage;
using System.IO;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace BuyTrainTicket
{
    public partial class MainPage : PhoneApplicationPage
    {

        // 构造函数
        public MainPage()
        {
            InitializeComponent();

            // 用于本地化 ApplicationBar 的示例代码
            //BuildLocalizedApplicationBar();
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
            String username;
            settings.TryGetValue<String>("username", out username);
            if (username != null)
            {
                Util.savePushUser(username.ToString());
            }
        }


        // 用于生成本地化 ApplicationBar 的示例代码
        //private void BuildLocalizedApplicationBar()
        //{
        //    // 将页面的 ApplicationBar 设置为 ApplicationBar 的新实例。
        //    ApplicationBar = new ApplicationBar();

        //    // 创建新按钮并将文本值设置为 AppResources 中的本地化字符串。
        //    ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative));
        //    appBarButton.Text = AppResources.AppBarButtonText;
        //    ApplicationBar.Buttons.Add(appBarButton);

        //    // 使用 AppResources 中的本地化字符串创建新菜单项。
        //    ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
        //    ApplicationBar.MenuItems.Add(appBarMenuItem);
        //}

        private void TextBlock_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NavigationService.Navigate(new Uri("/setting.xaml", UriKind.Relative));
        }

        private void TextBlock_Tap_2(object sender, System.Windows.Input.GestureEventArgs e)
        {
            string username;
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
            settings.TryGetValue<String>("username", out username);
            if (username == null)
            {
                MessageBox.Show("请先设置用户名和密码");
                NavigationService.Navigate(new Uri("/Setting.xaml", UriKind.Relative));
                return;
            }
            NavigationService.Navigate(new Uri("/QueryLeftTicket.xaml", UriKind.Relative));
        }

        private void PhoneApplicationPage_Loaded_1(object sender, RoutedEventArgs e)
        {
            Util.Dispatcher = Dispatcher;
            Util.NavigationService = NavigationService;
        }

        private void TextBlock_Tap_3(object sender, System.Windows.Input.GestureEventArgs e)
        {

            string username;
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
            settings.TryGetValue<String>("username", out username);
            if (username == null)
            {
                MessageBox.Show("请先设置用户名和密码");
                NavigationService.Navigate(new Uri("/Setting.xaml", UriKind.Relative));
                return;
            }
            NavigationService.Navigate(new Uri("/Order.xaml", UriKind.Relative));
        }

        private void TextBlock_Tap_4(object sender, System.Windows.Input.GestureEventArgs e)
        {
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
            string password;
            string username;
            settings.TryGetValue<String>("username", out username);
            settings.TryGetValue<String>("password", out password);
            if (username == null || password == null)
            {
                MessageBox.Show("请先设置用户名和密码");
                NavigationService.Navigate(new Uri("/Setting.xaml", UriKind.Relative));
                return;
            }
            sendRequest(Util.host + "/servlet/Buy12306Servlet?action=queryresult&password=" + password + "&username=" + username + "&type=queryresult&version=8.1");

        }

        void sendRequest(string url)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.BeginGetRequestStream(new AsyncCallback(getRequestCallback), request);
            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("网络错误，请稍后再试1");

                });
            }
        }

        void getRequestCallback(IAsyncResult asyncResult)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;

                Stream postStream = request.EndGetRequestStream(asyncResult);

                StringBuilder postData = new StringBuilder();
                postData.Append("");

                byte[] byteArray = Encoding.UTF8.GetBytes(postData.ToString());

                postStream.Write(byteArray, 0, byteArray.Length);
                postStream.Close();

                request.BeginGetResponse(new AsyncCallback(getResponseCallback), request);
            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("网络错误，请稍后再试2");

                });
            }
        }

        void getResponseCallback(IAsyncResult asyncResult)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);

                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    byte[] byteArray = new byte[response.ContentLength];
                    response.GetResponseStream().Read(byteArray, 0, (int)response.ContentLength);
                    String responseStr = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
                    JObject responseObj = JsonConvert.DeserializeObject<JObject>(responseStr);
                    JToken errMsgToken = responseObj.GetValue("errMsg");
                    Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show((string)errMsgToken);
                    });

                }
                else
                {
                    Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show(response.StatusCode.ToString());
                    });
                }
            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("网络错误，请稍后再试3");

                });
            }

        }

        private void TextBlock_Tap_5(object sender, System.Windows.Input.GestureEventArgs e)
        {
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
            string password;
            string username;
            settings.TryGetValue<String>("username", out username);
            settings.TryGetValue<String>("password", out password);
            if (username == null || password == null)
            {
                MessageBox.Show("请先设置用户名和密码");
                NavigationService.Navigate(new Uri("/Setting.xaml", UriKind.Relative));
                return;
            }
            sendRequest(Util.host + "/servlet/Buy12306Servlet?action=querycontacts&password=" + password + "&username=" + username + "&type=querycontacts&version=8.1");

        }

        private void TextBlock_Tap_6(object sender, System.Windows.Input.GestureEventArgs e)
        {
            string username;
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
            settings.TryGetValue<String>("username", out username);
            if (username == null)
            {
                MessageBox.Show("请先设置用户名和密码");
                NavigationService.Navigate(new Uri("/Setting.xaml", UriKind.Relative));
                return;
            }
            NavigationService.Navigate(new Uri("/QueryTask.xaml", UriKind.Relative));
        }

        private void PhoneApplicationPage_GotFocus_1(object sender, RoutedEventArgs e)
        {
            Util.Dispatcher = Dispatcher;
            Util.NavigationService = NavigationService;
        }
    }
}